<!--用户信息页面-->
<template>
    <div>
        <div style="display: flex;align-items: center;justify-content: center">
            <el-input style="width: 200px" placeholder="查询账号" v-model="userid" clearable></el-input>
            <el-input style="width: 200px; margin: 0 10px" placeholder="查询姓名" v-model="username" clearable></el-input>
            <el-select style="width: 100px; margin: 0 10px" v-model="role" placeholder="查询角色" clearable>
                <el-option
                        v-for="item in roles"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <el-button type="primary" @click="load(1)">查询</el-button>
            <el-button type="info" @click="reset" plain>重置</el-button>
        </div>
        <div style="margin: 10px 0">
            <el-button type="primary" plain @click="handleAdd">新增</el-button>
            <el-button type="danger" plain @click="delBatch">批量删除</el-button>
            <el-button style="margin-left: 1045px" type="info" plain @click="exportData">批量导出</el-button>
        </div>
        <el-table :data="tableData"
                  stripe
                  :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666'}"
                  style="font-size: 14px"
                  @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
            <el-table-column prop="userid" label="账号" align="center"></el-table-column>
            <el-table-column prop="username" label="姓名" align="center"></el-table-column>
            <el-table-column prop="phone" label="手机" align="center"></el-table-column>
            <el-table-column label="头像" align="center">
                <template v-slot="scope">
                    <div style="display: flex; align-items: center; justify-content: center">
                        <el-image style="width: 50px; height: 50px; border-radius: 50%" v-if="scope.row.avatar"
                                  :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" align="center"></el-table-column>
            <el-table-column prop="major" label="学部专业" align="center"></el-table-column>
            <el-table-column prop="createdtime" label="创建时间" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="180">
                <template v-slot="scope" style="font-size: 14px">
                    <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0; display: flex; align-items: center; justify-content: center">
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="total">
            </el-pagination>
        </div>

<!--        弹窗-->
        <el-dialog title="用户信息" :visible.sync="fromVisible" width="30%">
            <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
                <el-form-item label="账号" prop="userid">
                    <el-input v-model="form.userid"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-radio-group v-model="form.role">
                        <el-radio label="学生"></el-radio>
                        <el-radio label="教师"></el-radio>
                        <el-radio label="管理员"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload
                            class="avatar-uploader"
                            action="http://localhost:9090/file/uploadavatar"
                            :headers="{ token: user.token }"
                            :file-list="form.avatar ? [form.avatar] : []"
                            list-type="picture"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                    >
                        <el-button type="primary">上传头像</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="学部" prop="major" >
                    <el-select v-model="form.major" placeholder="请选择学部">
                        <el-option
                                v-for="item in options"
                                :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="fromVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {cellphoneValidator} from "@/utils/userPhone";

    export default {
        name: "User",
        data() {
            return {
                tableData:[], //所有的数据
                pageNum: 1, //当前的页码
                pageSize: 6, //每页显示的个数
                username: '',
                userid: '',
                role: '',
                total: 0, //默认是0
                fromVisible: false,
                //角色
                roles: [{
                    value: '学生',
                    label: '学生'
                }, {
                    value: '教师',
                    label: '教师'
                }, {
                    value: '管理员',
                    label: '管理员'
                }],
                //学部
                options: [],
                form: {},
                user: JSON.parse(localStorage.getItem("honey-user") || '{}'),//拿取个人用户信息
                rules: {
                    userid: [
                        {required: true, message: '请输入学号/工号', trigger: 'blur'}
                    ],
                    phone:[
                        {required: true, message:'请输入手机号', trigger:'blur'},
                        { validator: cellphoneValidator, trigger: 'blur' }
                    ],
                    major:[
                        {required: true, message:'请选择学部', trigger:'blur'},
                    ],
                    role:[
                        {required: true, message:'请选择角色', trigger:'blur'},
                    ],
                },
                ids: []
            }
        },
        created() {
            this.load()
        },
        methods: {
            exportData(){ //批量导出数据
                if(!this.ids.length){ //没有选择数据的时候,全部导出 或者根据搜索条件导出
                    window.open('http://localhost:9090/user/export?token=' + this.user.token
                        + "&userid=" + this.userid + "&id=" + this.id + "&role=" + this.role
                    )//后台导出接口
                }else {
                    //将ids数组转换成字符串 [1,2,3] => '1,2,3'
                    let idStr = this.ids.enroll(',')//选中行
                    window.open('http://localhost:9090/user/export?token=' + this.user.token
                        + "&ids=" + idStr)
                }
            },
            beforeAvatarUpload(file) {//限制文件上传格式和大小
                // const isJPG = file.type === 'image/jpeg';
                const testmsg = /^image\/(jpeg|png|jpg)$/.test(file.type);
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!testmsg) {
                    this.$message.error('上传头像图片格式错误!');
                }
                if (!isLt2M) {
                    setTimeout(() => {
                        this.$message.error('上传头像图片大小不能超过 2MB!');
                    }, 10);
                }
                return isLt2M && testmsg;
            },
            delBatch(){ //批量删除
                if (!this.ids.length){
                    this.$message.warning('请选择数据')
                    return
                }
                this.$confirm('确认批量删除这些数据吗？','确认删除',{type: "warning"}).then(response => {
                    this.$request.delete('/user/delete/batch', {
                        data: this.ids
                    }).then(res => {
                        if (res.code === '200'){ //操作成功
                            this.$message.success('操作成功')
                            this.load(1) //刷新表格数据
                        }else { //操作失败
                            this.$message.error(res.msg) //弹出错误信息
                        }
                    })
                }).catch(() => {})
            },
            handleSelectionChange(rows){ //选中的数据 rows:当前选中的所有行数据
                this.ids = rows.map(v => v.id)
            },
            del(id){ //单个删除
                this.$confirm('确认删除？','确认删除',{type: "warning"}).then(response => {
                    this.$request.delete('/user/delete/' + id).then(res => {
                        if (res.code === '200'){ //操作成功
                            this.$message.success('操作成功')
                            this.load(1) //刷新表格数据
                        }else { //操作失败
                            this.$message.error(res.msg) //弹出错误信息
                        }
                    })
                }).catch(() => {})
            },
            handleEdit(row){ //编辑
                this.form = JSON.parse(JSON.stringify(row)) //给form对象赋值 注意要深拷贝数据
                this.fromVisible = true //打开弹窗
            },
            handleAdd(){
                this.form = {} //新增数据的时候清空数据
                this.fromVisible = true //打开新增弹窗
            },
            save(){ //保存
                this.$refs.formRef.validate((valid) => {
                    if(valid){ //验证通过
                        this.$request({
                            url: this.form.id ? '/user/update' : '/user/add',
                            method: this.form.id ? 'PUT' : 'POST', //判断有无id,有为编辑,无为新增
                            data: this.form
                        }).then(res => {
                            if (res.code === '200'){ //成功保存
                                this.$message.success('保存成功')
                                this.load(1)
                                this.fromVisible = false
                            }else { //保存失败
                                this.$message.error(res.msg) //弹出错误信息
                            }
                        })

                    }
                })
            },
            reset(){
                this.username = ''
                this.userid = ''
                this.role = ''
                this.load()
            },
            load(pageNum){ //分页查询
                if (pageNum){
                    this.pageNum = pageNum
                }
                this.$request.get('/user/selectByPage', {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        username: this.username,
                        userid: this.userid,
                        role: this.role
                    }
                }).then(res => {
                    this.tableData = res.data.records
                    this.total = res.data.total
                })
                //接收学部类型值
                this.$request.get('/faculty/selectAll').then(res => {
                    this.options = res.data
                    console.log(res)
                    console.log(this.options)
                })
            },
            handleCurrentChange(pageNum){
                this.load(pageNum)
            },
            handleAvatarSuccess(response, file, fileList) {
                //把user的头像属性换成上传的头像链接
                this.form.avatar = response.data
            }
        }
    }

</script>

<style scoped>

</style>